#!/usr/bin/env python

import smtplib
import os
import sqlite3
import cgi
import string
import random
import datetime

def hs_generator(size=6, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

conn = sqlite3.connect('/db/metanode.db')
cur = conn.cursor()
#cur.execute("DROP TABLE idare_jobs;")
#cur.execute("CREATE TABLE idare_jobs(name text, email text, org text, project text, imgformat text, handshake text, status text default 'new', jobid INTEGER PRIMARY KEY AUTOINCREMENT);")

qform = cgi.FieldStorage()
name = qform.getvalue('name')
if (name == None):
    name = "none - for testing only"
email = qform.getvalue('email')
hs = hs_generator();

cur.execute("INSERT INTO idare_jobs (name, email, org, handshake) VALUES('" + name + "','" + email + "','uta','" + hs +"');")
lid = cur.lastrowid
logfile = open('metanode.log', 'a')
logfile.write("started init jobid " + str(lid) + " datetime " + datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y") + "\nuser_email " + name + "_"+ email +"\n")
#print "The last Id of the inserted row is %d" % lid
#create config file

#/db/jobs
os.system('mkdir /db/jobs/_' + str(lid))
os.system('chmod 777 /db/jobs/_' + str(lid))
os.system('mkdir /db/jobs/_' + str(lid) + '/input')
os.system('mkdir /db/jobs/_' + str(lid) + '/output')
os.system('chmod 777 /db/jobs/_' + str(lid) + '/output')
os.system('chmod 777 /db/jobs/_' + str(lid) + '/input')

#made config file
os.system('touch /db/jobs/_' + str(lid) + '/jobinfo.config')
os.system('chmod 777 /db/jobs/_' + str(lid) + '/jobinfo.config')
fjs = open('/db/jobs/_' + str(lid) + '/jobinfo.config', 'w')

project = qform.getvalue('project')
org = qform.getvalue('org')
imageformat=qform.getvalue('imageformat')

fjs.write("name:"+name+"\n")
fjs.write("email:"+email+"\n")
fjs.write("project:"+project+"\n")
fjs.write("org:"+org+"\n")
fjs.write("handshake:"+hs+"\n")
fjs.write("jobID:"+str(lid)+"\n")
fjs.write("IDAREImageFileFormat:"+imageformat +"\n")
fjs.write("input:"+ "/db/jobs/_" + str(lid) + "/input/\n")
fjs.write("output:"+ "/db/jobs/_" + str(lid) + "/output/\n")

inmax = qform.getvalue('inmax')
filemax = int(inmax)
for i in range(0,filemax):
    infile = qform['file_' + str(i)]  
    if infile != None and infile.filename:
        fn = os.path.basename(infile.filename)
	mli = str(i+1) 
	open('/db/jobs/_' + str(lid) + "/input/" + fn, 'w').write(infile.file.read())
	os.system('chmod 755 /db/jobs/_' + str(lid) + "/input/" + fn)
        fjs.write("DataSetFileName" + mli + ":" + fn + "\n")
	fjs.write("DataSetType" + mli + ":" + qform.getvalue('type_' + str(i)) + "\n")
	fjs.write("DataSetColorScheme" + mli + ":" + qform.getvalue('cs_' + str(i)) + "\n")
	fjs.write("DataSetDescription" + mli + ":" + qform.getvalue('desc_' + str(i)) + "\n")

#http://idare-server.uni.lu/cgi-bin/update_idare.cgi?jobid=11&handshake=89D0E2&status=status
"""
DataSetFileName1:H3K4Data.xlsx
DataSetFileName2:PredictionData.csv
DataSetFileName3:GraphData.xlsx
  DataSetDescription4:Transcription factor Data for several Transcription factors associated with the genes
  DataSetDescription5:
    DataSetDescription6:
    DataSetDescription7:
    DataSetDescription8:
    DataSetDescription9:
    ImageFileFormat:png
keep counter - what is minimum set?
file_0 ..file_8
each file has a type and description
for i in range(0,9):
  
rawfile = qform['rawf']
    statfile = qform['statf']
    addfile = qform['additionalf']
    rawfn = ""
    statfn = ""
    additionalfn = ""
    if (external == None):
        external = ""
    if (not os.path.exists('/var/www/gcmsjob' + external + '/results/' + jobid)):
        os.system("mkdir /var/www/gcmsjob" + external + "/results/" + jobid)
    if rawfile.filename:
        # strip leading path from file name to avoid 
        # directory traversal attacks
        fn = os.path.basename(rawfile.filename)
        rawfn = fn
        open('/var/www/gcmsjob' + external + '/results/' + jobid + '/' + fn, 'w').write(rawfile.file.read())
    if statfile.filename:
        fn = os.path.basename(statfile.filename)
        statfn = fn
        open('/var/www/gcmsjob' + external + '/results/' + jobid + '/' + fn, 'w').write(statfile.file.read())
    if addfile.filename:
        fn = os.path.basename(addfile.filename)
        additionalfn = fn
        open('/var/www/gcmsjob' + external + '/results/' + jobid + '/' + fn, 'w').write(addfile.file.read())
"""

fjs.close()
conn.commit()
conn.close()

logfile.write("done init jobid " + str(lid) + " handshake " + hs + "\n")
#anything to log for calling invocation script? return status
#logfile.close()

#invoking metanode server generation
try:
    logfile.write('calling python /home/idare/IDARE/StartScript.py /db/jobs/_' + str(lid) + '/jobinfo.config\n')
    os.system('python /home/idare/IDARE/StartScript.py /db/jobs/_' + str(lid) + '/jobinfo.config >> /home/idare/IDARE/IDAREInit.log 2>&1'  )
    
except Exception, e:
    logfile.write("Exception on system StartScript.py init jobid " + str(lid) + " " + str(e) + "\n" )
    logfile.close()


def sendMail(pname, receivers, jobid, url):
    initials = pname.split("@")[0]
    sender = 'jake.lin@uni.lu'
    #receivers.append("christian.jaeger@uni.lu")
    message = """From: IDARE Metanode Server <thomas.pfau@uni.lu>
To: User
Subject: %s

%s
    """ %(jobid + "_" + initials, "Hello " + pname + ",\n\nYour Metanode job was submitted successfully and the nodes are now being generated. \n You will get another email once your nodes have successfully been generated.\n\nCheers and feel free to contact Thomas Pfau with questions.")

    try:
        smtpObj = smtplib.SMTP('localhost')
        smtpObj.sendmail(sender, receivers, message)
    except SMTPException:
        print "Error: unable to send email"

#os.system('touch /var/www/metanodeui/data/_100.out')
sendMail(name, [email, "jake.lin@student.tut.fi"], "IDARE job initialized: " + str(lid), "http://idare-server.uni.lu/metanodeui/index.html?jobID=" + str(lid) + "&hs=" + hs)
logfile.close()

print "Content-Type: text/html"
print
print """\
<html>
<body>
<h2>Job submitted %s</h2>
</body>
</html>
""" %(str(lid))
